#include "comm.hpp"

int main()
{
    int k = ftok(PATH_NAME, PROJ_ID);
    if (k < 0)
    {
        Log(" create key failed", Error) << " client key : " << k << endl;
        exit(1);
    }
    Log(" create key done", Debug) << " client key : " << k << endl;

    // 获取共享内存
    int shmid = shmget(k, SHM_SIZE, 0);
    if (shmid < 0)
    {
        Log(" create shm faild", Error) << " client key : " << k << endl;
        exit(2);
    }
    Log(" create shm success", Debug) << " client key : " << k << endl;

    // 链接
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    if (shmaddr == nullptr)
    {
        Log(" attach shmaddr failed", Error) << " client key : " << k << endl;
        exit(3);
    }
    Log(" attach shmaddr success", Debug) << " client key : " << k << endl;

    //使用
    //client将共享内存看做一个char 类型的buffer

     int fd=OpenFIFO(FIFO_NAME,WRITE);
     while(true)
     {
        ssize_t s=read(0,shmaddr,SHM_SIZE-1);//从键盘读取数据到缓冲区(shm)
        if(s>0)
        {
            shmaddr[s-1] = 0;
            Signal(fd);//唤醒管道，Server正常读取shm内容
             if(strcmp(shmaddr,"quit") == 0) break;
        }
     }
    CloseFifo(fd);



    // char a = 'a';
    // for (; a <= 'z'; a++)
    // {
    //     // 我们是每一次都向shmaddr[共享内存的起始地址]写入
    //     snprintf(shmaddr, SHM_SIZE - 1,
    //              "hello server, 我是其他进程,我的pid: %d, inc: %c\n",
    //              getpid(), a);
    //     sleep(5);
    // }


    // 去关联
    int n = shmdt(shmaddr);
    assert(n != -1);
    Log(" detach shmdt success", Error) << " client key : " << k << endl;

    // client是客户端 ，不需要shmctl删除

    return 0;
}